package com.qifan.energy.fragment;


import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.qifan.energy.base.BaseFragment;
import com.qifan.energy.bean.result.PayOrderWechatResult;
import com.qifan.energy.bean.vo.GenerateOrderParamVO;
import com.qifan.energy.BuildConfig;
import com.qifan.energy.R;
import com.qifan.energy.adapter.OrderReadyPayAdapter;
import com.qifan.energy.bean.result.OrderItem;
import com.qifan.energy.bean.result.Page2;
import com.qifan.energy.bean.result.Pagination2;
import com.qifan.energy.global.Keys;
import com.qifan.energy.global.Values;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.net.RequestParams;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.ActivityStackUtil;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.widget.dialog.LoadingUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


public class OrderReadyPayFragment extends BaseFragment {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private List<OrderItem> dataList = new ArrayList();
    private OrderReadyPayAdapter adapter;
    private int pageNum = 1;
    private IWXAPI wxapi;
    private int orderId = 0;//订单Id

    public static OrderReadyPayFragment newInstance() {
        return new OrderReadyPayFragment();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_order_all;
    }

    @Override
    protected void initView(View view) {

        changeStatusWhiteFontBlack();

        adapter = new OrderReadyPayAdapter(dataList);
        /* 监听子控件点击 */
        adapter.setOnItemChildClickListener(this::onItemChildClick);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .sizeResId(R.dimen.dp_10)
                .colorResId(R.color.divider_color)
                .build());

        /* 加载更多 */
        adapter.setOnLoadMoreListener(()->{
            orderListMore();
        },recyclerView);

        //添加空布局
        adapter.setEmptyView(getEmptyDataView());
    }

    /* 点击子控件 */
    private void onItemChildClick(BaseQuickAdapter a, View v, int p) {
        final OrderItem item = (OrderItem)a.getData().get(p);
        switch (v.getId()) {
            case R.id.cancel_order_tv:
                orderCancelUserOrder(item.getId());
                break;
            case R.id.pay_order_tv:
                orderId = item.getId();
                //获取签名信息
                GenerateOrderParamVO orderParamVO = new GenerateOrderParamVO();
                orderParamVO.setOrderId(item.getId());//订单号
                orderParamVO.setPayType(Values.PayType.WEIXIN);//微信支付
                orderWXPay(orderParamVO);
                break;
            default:
                break;
        }
    }

    @Override
    public void initData() {
        orderList();
    }

    /* 获取空布局 */
    private View getEmptyDataView() {
        return getLayoutInflater().inflate(R.layout.order_list_empty, recyclerView, false);
    }

    /* 下来刷新 */
    private void orderList(){
        pageNum = 1;
        NetUtils.orderList(RequestParams.ORDERTYPE.DAIFU, pageNum, Pagination2.PAGESIZE_10, new MyObserver<Page2<OrderItem>>(getActivity()) {
            @Override
            public void onSuccess(Page2<OrderItem> page2) {
                if (null != page2) {
                    dataList = page2.getList();
                    adapter.setNewData(page2.getList());
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 上拉加载 */
    private void orderListMore() {
        ++pageNum;
        NetUtils.orderList(RequestParams.ORDERTYPE.DAIFU, pageNum, Pagination2.PAGESIZE_10, new MyObserver<Page2<OrderItem>>(getActivity()) {
            @Override
            public void onSuccess(Page2<OrderItem> page2) {
                if (null != page2) {
                    dataList.addAll(page2.getList());
                    boolean isNoMore = (dataList.size() >= page2.getTotal());
                    adapter.setEnableLoadMore(!isNoMore);
                    if (isNoMore) {
                        adapter.loadMoreEnd();
                    } else {//刷新数据
                        adapter.setNewData(dataList);
                    }
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 用户取消订单 */
    private void orderCancelUserOrder(Integer orderId){
        NetUtils.orderCancelUserOrder(orderId, new MyObserver<String>(getActivity()) {
            @Override
            public void onSuccess(String result) {
                ToastUtils.showShort("已取消订单");
                //刷新数据
                orderList();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    //生成订单签名信息(微信)
    private void orderWXPay(final GenerateOrderParamVO orderParamVO){
        LoadingUtils.show(getActivity());
        NetUtils.orderWXPay(orderParamVO,new MyObserver<PayOrderWechatResult>(getActivity()) {
            @Override
            public void onSuccess(PayOrderWechatResult result) {
                Logger.i("paySign:" + result.toString());
                //FastPayUtil.create(ConfirmOrderActivity.this).startWechatPay(result);
                //调起微信支付
                startWechatPay(result);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 发起微信支付 */
    public void startWechatPay(PayOrderWechatResult result) {
        //这里的appid，替换成自己的即可
        wxapi = WXAPIFactory.createWXAPI(getActivity(), BuildConfig.WX_APPKEY,true);
        wxapi.registerApp(BuildConfig.WX_APPKEY);
        //这里的bean，是服务器返回的json生成的bean
        PayReq payRequest = new PayReq();
        payRequest.appId = result.getAppid();
        payRequest.nonceStr = result.getNoncestr();
        payRequest.partnerId = result.getPartnerid();
        payRequest.prepayId = result.getPrepayid();
        payRequest.packageValue = result.getPackageValue();//固定值
        payRequest.sign = result.getSign();
        payRequest.signType = result.getSignType();
        payRequest.timeStamp = result.getTimestamp();

        //发起请求，调起微信前去支付
        boolean isSuccess = wxapi.sendReq(payRequest);
        if (isSuccess){
            SharedPreferencesUtil.putData(Keys.ORDER_ID_KEY,orderId);
            LoadingUtils.hide();
        } else {
            LoadingUtils.hide();
            ToastUtils.showShort("支付失败");
            ActivityStackUtil.finishTopActivity();
        }
    }
}
